package com.yanxi.interceptor;

import com.yanxi.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    public static final Logger log = LoggerFactory.getLogger(TokenInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.获取请求路径
        String requestURI =request.getRequestURI();

        //2.判断是否为登录请求
        if(requestURI.contains("/login")){
            log.info("登录操作,放行");
            return true;
        }

        //3.获取请求头token
        String token = request.getHeader("token");

        //4.判断token是否为空,如果为空,则返回错误结果
        if(token == null || token.isEmpty()){
            log.info("请求头token为空,返回错误结果");
            response.setStatus(401);
            return  false;
        }

        //5.不是空,则解析token,失败则返回错误结果,成功则放行
        try {
            JwtUtils.parseToken( token);
        } catch (Exception e) {
            log.info("解析令牌失败,返回错误结果");
            response.setStatus(401);
            return  false;
        }

        //6.放行
        log.info("令牌合法,放行");
        return true;
    }
}
